package dbtool

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"strings"
)

type Tabler interface {
	TableName() string
}

type GormDAO struct {
	db        *gorm.DB
	index     *gorm.DB
	tableName string
}

func (m *GormDAO) Init(db *gorm.DB, item Tabler) {
	db.AutoMigrate(item)
	m.db = db
	m.index = db.Model(item)
	m.tableName = item.TableName()
	TableMap[m.tableName] = item
}

func (m *GormDAO) ValidDB(db *gorm.DB) *gorm.DB {
	if db == nil {
		return m.db
	} else {
		return db
	}
}

func (m *GormDAO) AddIndex(fields ...string) {
	if len(fields) == 0 {
		return
	}
	idxName := fmt.Sprintf("idx_%s_%s", m.tableName, strings.Join(fields, "_"))
	m.index.AddIndex(idxName, fields...)
}

func (m *GormDAO) AddUniqueIndex(fields ...string) {
	if len(fields) == 0 {
		return
	}
	idxName := fmt.Sprintf("idx_%s_%s", m.tableName, strings.Join(fields, "_"))
	m.index.AddUniqueIndex(idxName, fields...)
}
